from fastapi import APIRouter, Request, Depends, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from typing import List, Dict, Any

from app.core.config import config
from app.database.crud import get_db
from app.services.data_collector import DataCollector
from app.services.user_profile import UserProfileService

router = APIRouter()
templates = Jinja2Templates(directory="app/templates")
data_collector = DataCollector()
user_service = UserProfileService()

@router.get("/admin", response_class=HTMLResponse)
async def admin_dashboard(request: Request):
    """管理仪表板"""
    data_stats = data_collector.get_data_stats()
    
    return templates.TemplateResponse(
        "admin.html",
        {
            "request": request,
            "data_stats": data_stats,
            "model_paths": config.get_model_paths()
        }
    )

@router.get("/admin/data", response_class=HTMLResponse)
async def data_viewer(request: Request, page: int = 1, model: str = None):
    """数据查看界面"""
    db = next(get_db())
    
    query = db.query(InteractionRecord)
    if model:
        query = query.filter(InteractionRecord.model_used == model)
    
    total_records = query.count()
    records = query.order_by(InteractionRecord.created_at.desc()).offset((page-1)*50).limit(50).all()
    
    return templates.TemplateResponse(
        "data_viewer.html",
        {
            "request": request,
            "records": records,
            "current_page": page,
            "total_pages": (total_records + 49) // 50,
            "selected_model": model
        }
    )

@router.get("/admin/profiles", response_class=HTMLResponse)
async def user_profiles(request: Request):
    """用户画像界面"""
    db = next(get_db())
    users = db.query(UserProfile).order_by(UserProfile.updated_at.desc()).limit(100).all()
    
    user_stats = []
    for user in users:
        stats = user_service.get_user_stats(user.user_id)
        user_stats.append(stats)
    
    return templates.TemplateResponse(
        "user_profiles.html",
        {
            "request": request,
            "user_stats": user_stats
        }
    )

@router.post("/admin/export-training-data")
async def export_training_data(model: str = None, min_quality: float = 0.7):
    """导出训练数据API"""
    result = data_collector.export_training_data(model, min_quality)
    return {"message": result}

@router.get("/admin/api/stats")
async def get_system_stats():
    """获取系统统计API"""
    data_stats = data_collector.get_data_stats()
    
    return {
        "system_stats": data_stats,
        "config": {
            "model_paths": config.get_model_paths(),
            "data_collection_enabled": config.get_bool('DATA_COLLECTION_ENABLED')
        }
    }